import React, {
    Component
} from "react";
import GridTable from '../../../components/display/gridTable';
import {
    remoteUpdateList,
    getTypeIdOrFrameWork,
    stubRemoteUpdate
} from "../../../fetch/fetchApi";
import {
    Button,
    Input,
    Row,
    Col,
    Select,
    Divider,
    Modal,
    Form,
    Upload,
    Icon,
    Progress,
    DatePicker,
    message,
    Spin
} from 'antd';
import locale from "antd/lib/date-picker/locale/zh_CN";
import moment from 'moment';
import RemoteUpgrade from '../stubQuery/remoteUpgrade';
import UpgradeSuccessModal from '../stubQuery/upgradeSuccessModal';
const Option = Select.Option;
const FormItem = Form.Item;
const {
    TextArea
} = Input;
const {
    RangePicker
} = DatePicker;

const upgradeStatus = {
    "-1": "全部",
    "0": "进行中",
    "1": "升级成功",
    "2": "升级失败"
}
const startDefaultDate = moment().subtract(7, 'days');
const endDefaultDate = moment();
class RemoteUpgradeIndex extends Component {
    constructor(props) {
        super(props);
        this.init();
        this.state = {
            data: [],
            pagination: {},
            loading: false,
            visible: false,
            selectedRowKeys: [],
            selectedRows: []
        };
    }

    componentDidMount() {
        this.setState({
            rangeValue: [startDefaultDate, endDefaultDate]
        })
        this.fetch();
    }

    getProgressByStatus = (params = {}) => {
        if (!params.status.toString()) {
            return "--";
        }
        if (params.status.toString() === "0") {
            return <Progress percent={params.rate || 1} status="active" />;
        } else if (params.status.toString() === "1") {
            return <Progress percent={100} />;
        } else {
            return <Progress percent={50} status="exception"/>;
        }
    }

    combineOptions = (json) => {
        if (!json) {
            return;
        }
        const options = [];
        for (let item in json) {
            options.push(<Option value={item}>{json[item]}</Option>);
        }
        return options;
    }

    init() {
        this.query = {
            page: 1,
            pagecount: 10,
            startTime: startDefaultDate.format("YYYY-MM-DD"),
            endTime: endDefaultDate.format("YYYY-MM-DD")
        };

        this.tableColumns = [{
            title: '电桩编号',
            dataIndex: 'stubId',
            fixed: 'left',
            width: 100
        }, {
            title: '设备型号',
            dataIndex: 'modelNo'
        }, {
            title: '版本型号',
            dataIndex: 'typeId'
        }, {
            title: '升级版本',
            dataIndex: 'frameWork'
        }, {
            title: '升级进度',
            dataIndex: 'otaRate',
            render: (text, record) => (
                <div>
                        {this.getProgressByStatus({
                        status: record.status,
                        rate: text
                    })}
                    </div>
            )
        }, {
            title: '执行时间',
            dataIndex: 'otaStartTime'
        }, {
            title: '执行人',
            dataIndex: 'updatePerson'
        }, {
            title: '执行结果',
            dataIndex: 'status',
            render: (text, record) => (
                <div>
                        <div>
                            {upgradeStatus[text]}
                        </div>
                        <div>
                            {text.toString() === "2" && record.endInfo && "(原因：" + (record.endInfo) + ")"}
                        </div>
                    </div>
            )
        }, {
            title: '操作',
            key: 'operation',
            fixed: 'right',
            width: 100,
            render: (text, record) => (
                <div>{record.status.toString() === "2" ? <a href='javascript:void(0);' onClick={(e) => this.handleReUpgradeClick(record)}>重新升级</a> : "--"}</div>
            )
        }];

    }

    handleReUpgradeClick = (record) => {
        this.stubRemoteUpdate(record).then((res) => {
            if (res.data.code === '200') {
                this.setState({
                    upgradeSuccessModalVisible: true,
                    selectedRowKeys: [],
                    selectedRows: []
                })
            }
        })
    }

    async stubRemoteUpdate(record) {
        return await stubRemoteUpdate({
            stubIds: record.stubId,
            typeId: record.typeId,
            frameWork: record.frameWork
        })
    }

    handleRemoteUpgrade = (e) => {
        this.upgradeParams = e;
    }

    showModal = () => {
        this.setState({
            visible: true,
        });
    }

    async remoteUpdateList() {
        return await remoteUpdateList(this.query);
    }

    queryHandler = () => {
        this.query["page"] = 1;
        this.fetch();
    }

    fetch = (params = {}) => {
        this.setState({
            loading: true
        });
        this.remoteUpdateList().then((res) => {
            if (!res) {
                return;
            }
            const pagination = this.state.pagination;
            pagination.total = res.data.pageLimit.totalCount;
            pagination.current = params.current || 1;
            pagination.onChange = (page, pageSize) => {
                this.query["page"] = page;
                this.query["pagecount"] = pageSize;
                this.fetch({
                    current: page
                });
            }
            this.setState({
                loading: false,
                data: res.data.data,
                selectedRowKeys: [],
                selectedRows: [],
                pagination
            });
        }).catch((ex) => {
            console.log(ex);
        });
    }

    handleCancel = (e) => {
        this.setState({
            visible: false,
        });
    }

    handleChange = (dates) => {
        const startDate = dates[0];
        const endDate = dates[1];
        if (!startDate || !endDate) {
            this.query.startTime = null;
            this.query.endTime = null;
            this.setState({
                rangeValue: null
            });
            return;
        }
        if (endDate.diff(startDate, 'days') > 7) {
            message.error('查询时间只能在7天以内');
            this.query.startTime = null;
            this.query.endTime = null;
            this.setState({
                rangeValue: null
            });
        } else {
            this.query.startTime = startDate.format("YYYY-MM-DD");
            this.query.endTime = endDate.format("YYYY-MM-DD");
            this.setState({
                rangeValue: dates
            });
        }
    }

    handleStatusChange = (e) => {
        if (e === "-1") {
            this.query.status = null;
        } else {
            this.query.status = e;
        }
    }

    handleStubIdChange = (e) => {
        this.query.stubId = e.target.value;
    }

    handleDeviceTypeChange = (e) => {
        this.query.modelNo = e.target.value;
    }

    handleVersionChange = (e) => {
        this.query.typeId = e.target.value;
    }

    handleFrameWorkChange = (e) => {
        this.upgradeParams.frameWork = e;
        this.setState({
            frameWorkValue: e
        })
    }

    handleUpSuccessModalCancel = () => {
        this.setState({
            upgradeSuccessModalVisible: false
        })
    }

    async batchRemoteUpgrade() {
        const selectedRows = this.state.selectedRows;
        if (selectedRows.length === 0) {
            message.error("请至少选择一项！")
            return;
        }
        this.setState({
            batchBtnLoading: true
        })
        let count = 0;
        const promises = selectedRows.map((item, index) => {
            const response = this.stubRemoteUpdate(item);
            return response;
        })
        for (let promise of promises) {
            console.log(await promise);
            if ((await promise).data.code === "200") {
                count++;
            }
        }
        if (count > 0 && count === selectedRows.length) {
            message.success("操作成功！");
        } else if (count > 0 && count < selectedRows.length) {
            message.success("部分桩操作成功！");
        } else if (count === 0 && selectedRows.length > 0) {
            message.error("操作失败！");
        }
        this.setState({
            selectedRowKeys: [],
            selectedRows: [],
            batchBtnLoading: false
        })
    }

    handleBatchBtnClick = () => {
        this.batchRemoteUpgrade();
    }

    render() {
        const formItemLayout = {
            labelCol: {
                span: 4
            },
            wrapperCol: {
                span: 16,
                offset: 3
            }
        };

        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(selectedRows);
                this.setState({
                    selectedRowKeys,
                    selectedRows
                });
            },
            getCheckboxProps: record => ({
                disabled: record.status === null || record.status.toString() !== "2"
            }),
            onSelect: (record, selected, selectedRows, nativeEvent) => {


            },
            onSelectAll: (selected, selectedRows, changeRows) => {

            }
        };

        const Content = <div className="sc-page-content">
            <div className="page-toolbar">
                <Row gutter={8}>
                    <Col lg={6} xl={6}>
                        <RangePicker format="YYYY-MM-DD" locale={locale} value={this.state.rangeValue} onChange={this.handleChange}/>
                    </Col>
                    <Col lg={4} xl={4} className="whole-fill">
                        <Input placeholder="电桩编号精确查询" onChange={this.handleStubIdChange}/>
                    </Col>
                    <Col lg={2} xl={2} className="whole-fill">
                        <Input placeholder="设备型号" onChange={this.handleDeviceTypeChange}/>
                    </Col>
                    <Col lg={2} xl={2} className="whole-fill">
                        <Input placeholder="版本型号" onChange={this.handleVersionChange}/>
                    </Col>
                    <Col lg={2} xl={2} className="whole-fill" style={{'width': '120px'}}>
                        <Select placeholder="执行结果" onChange={this.handleStatusChange} defaultValue="-1">
                            {this.combineOptions(upgradeStatus)}
                        </Select>
                    </Col>
                    <div  className="button-inlineBlock">
                        <Button type="primary" onClick={this.queryHandler}>查询</Button>
                    </div>
                    <div  className="button-inlineBlock">
                        <Button type="primary" loading={this.state.batchBtnLoading} onClick={this.handleBatchBtnClick}>批量升级</Button>
                    </div>
                </Row>
            </div>
            <div className="page-panel">
                <GridTable rowSelection={rowSelection} postyle="table-center" data={this.state.data} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
            </div>
            { /*<Modal title="远程升级" visible={this.state.visible} confirmLoading={this.state.confirmLoading} width="500px" onOk={this.handleOk} onCancel={this.handleCancel}>
                <RemoteUpgrade params={this.state.remoteUpgradeParams} handle={this.handleRemoteUpgrade}/>
            </Modal>*/ }
            <UpgradeSuccessModal onAdd={this.props.onAdd} handleCancel={this.handleUpSuccessModalCancel} visible={this.state.upgradeSuccessModalVisible}/>
        </div>;

        return Content;
    }
}

export default RemoteUpgradeIndex;